{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Markdown 数学公式 插件 mathjax\n",
    "[使用文档](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)  \n",
    "自定义 损失函数\n",
    "预测商品销量问题\n",
    "\\\\[Loss(y,y')=\\sum_{i=1}^{n}f(y_i,y_i')\\\\],  \\\\[f(x,y) =\\begin{cases}a(x-y) \\quad x\t> y\\\\b(y-x) \\quad x \\le y\\\\\\end{cases}\\\\]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from numpy.random import RandomState"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1.02001846]\n",
      " [ 1.0431807 ]]\n"
     ]
    }
   ],
   "source": [
    "batch_size = 8 \n",
    "#两个输入节点\n",
    "x = tf.placeholder(tf.float32,shape=(None,2),name='x-input')\n",
    "# 回归问题一般只有一个输出节点\n",
    "y_ = tf.placeholder(tf.float32,shape=(None,1),name = 'y-input')\n",
    "\n",
    "#定义了一个单层的神经网络前向传播的过程,这里是简单的加权和.\n",
    "w1 = tf.Variable(tf.random_normal([2,1],stddev=1))\n",
    "y = tf.matmul(x,w1)\n",
    "\n",
    "#定义预测多了和预测少了的成本\n",
    "loss_less = 10\n",
    "loss_more = 1\n",
    "loss = tf.reduce_sum(tf.where(tf.greater(y,y_),(y-y_)*loss_more,(y_-y)*loss_less))\n",
    "train_step = tf.train.AdamOptimizer(0.001).minimize(loss)\n",
    "\n",
    "#通过随机数生成一个模拟数据集\n",
    "rdm = RandomState(1)\n",
    "dataset_size = 128\n",
    "X = rdm.rand(dataset_size,2)\n",
    "#设置回归的正确值为两个输入和加上一个随机量.之所以要加上一个随机量是为了\n",
    "#加入不可预测的噪音,否则不同损失函数的意义就不大,因为不同损失函数都会在能\n",
    "#完全预测正确的时候最低.一般来说噪音为一个均值为0的小量,所以这里的噪音设置为-0.05~0.05 的随机数.\n",
    "Y = [[x1 + x2 + rdm.rand()/10.0-0.05] for (x1,x2) in X]\n",
    "\n",
    "#训练 神经网络\n",
    "with tf.Session() as sess:\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    STEPS = 5000\n",
    "    for i in range(STEPS):\n",
    "        start = (i * batch_size) % dataset_size\n",
    "        end = min(start+batch_size,dataset_size)\n",
    "        sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})\n",
    "        print(sess.run(w1))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
